/*
	This file is part of Lproxy.

    Lproxy is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Lproxy is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Lproxy.  If not, see <http://www.gnu.org/licenses/>.
*/
package lproxy_client;

import java.io.IOException;
import java.net.*;
import java.util.Map;

class ConnectClient extends Connection
{
	ConnectClient(Socket p_socket) throws Exception
	{
		this.m_socket = p_socket;
		this.m_out = this.m_socket.getOutputStream();
	}
	public void Send(byte[] p_data) throws Exception
	{
		try
		{
			this.m_out.write(p_data);
		}
		catch(IOException e)
		{
			throw new Exception("this.m_out.write(p_data) " + e.toString());
		}
		try
		{
			this.m_out.flush();
		}
		catch(IOException e)
		{
			throw new Exception("this.m_out.flush() " + e.toString());
		}
	}
	public String Receive() throws Exception
	{
		this.m_in = this.m_socket.getInputStream();
		String buffer = new String("");
		byte[] receive_buffer = new byte[this.MAX_BUFFER_SIZE];
		int len = 0;
		while(buffer.indexOf(CRLF+CRLF) == -1)
		{
			len = this.m_in.read(receive_buffer,0,this.MAX_BUFFER_SIZE);
			buffer += new String(receive_buffer,0,len);
		}
		Map<String,String> header = ParseHeader(buffer);
		if(header.get("method").equals("POST") || header.get("method").equals("PUT"))
		{
			int content_length = Integer.parseInt(header.get("content-length"));
			while(header.get("content").length() < content_length)
			{
				len = this.m_in.read(receive_buffer,0,this.MAX_BUFFER_SIZE);
				if(len == -1)
					break;
				buffer += new String(receive_buffer,0,len);
				header = ParseHeader(buffer);
			}
		}
		return buffer;
	}
	private Socket m_socket;
}
